package com.zheng.hospital.common.helper;

import com.alibaba.fastjson.JSONObject;
import com.zheng.hospital.common.util.HttpUtil;
import com.zheng.hospital.common.util.MD5;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class HttpRequestHelper {
    public static Map<String, Object> switchMap(Map<String, String[]> paramMap) {
        Map<String, Object> resultMap = new HashMap<>();
        for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
            resultMap.put(entry.getKey(), entry.getValue()[0]);
        }
        return resultMap;
    }

    /**
     * 获取请求签名
     * @param paramMap
     * @param signKey
     * @return
     */
    public static String getSign(Map<String, Object> paramMap, String signKey) {
        if (paramMap.containsKey("sign")){
            paramMap.remove("sign");
        }
        Map<String, Object> sorted = new TreeMap<>(paramMap);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> param : sorted.entrySet()) {
            sb.append(param.getValue()).append("|");
        }
        sb.append(signKey);
        sb.append(signKey);
        log.info("加密前：" + sb.toString());
        String md5Str = MD5.encrypt(sb.toString());
        log.info("加密后：" + md5Str);
        return md5Str;
    }

    /**
     * 验证签名
     * @param paramMap
     * @param signKey
     * @return
     */
    public static boolean isSignEquals(Map<String, Object> paramMap, String signKey) {
        String sign = (String)paramMap.get("sign");
        String md5Str = getSign(paramMap, signKey);
        if(!sign.equals(md5Str)) {
            return false;
        }
        return true;
    }

    /**
     * 当前时间戳
     * @return
     */
    public static long getTimestamp() {
        return new Date().getTime();
    }

    /**
     * 封装同步请求
     * @param paramMap
     * @param url
     * @return
     */
    public static JSONObject sendRequest(Map<String, Object> paramMap, String url) {
        String result = "";
        try {
            //封装post参数
            StringBuilder postParam = new StringBuilder();
            for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                postParam.append(param.getKey()).append("=")
                        .append(param.getValue()).append("&");
            }
            log.info(String.format("--> 发送请求：post data %1s", postParam));
            byte[] requestData = postParam.toString().getBytes("utf-8");
            byte[] responseData = HttpUtil.doPost(url, requestData);
            result = new String(responseData);
            log.info(String.format("--> 应答结果：result data %1s", result));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(result);
    }
}
